package com.keepers.repair.net;

import com.keepers.repair.model.XmlRootModel;

import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Response;
import retrofit2.adapter.rxjava2.Result;

/**
 * auth aboom
 * date 2018/10/21
 */
public class RxTransformerHelper {

    /**
     * 过滤器，result业务过滤 返回数据源
     */
    public static ObservableTransformer<Result<XmlRootModel>, String> applySchedulersResult() {
        return observable -> observable
                .compose(applySchedulersAndAllFilter())
                .map(result -> {
                    Response<XmlRootModel> response = result.response();
                    if (response != null) {
                        XmlRootModel body = response.body();
                        if (body != null) {
                            LogUtil.e("result json : " + body.content);
                            return body.content;
                        }
                    }
                    throw new Exception("data is null");
                });
    }

    /**
     * 过滤器， 业务过滤
     */
    public static <T> ObservableTransformer<T, T> applySchedulersAndAllFilter() {
        return upstream -> upstream
                .compose(applySchedulers())
                .doOnNext(t -> {
                    if (t instanceof Result) {
                        Result result = ((Result) t);
                        if (result.isError()) {
                            Throwable error = result.error();
                            throw new Exception(error == null ? "系统异常" : error.getMessage());
                        }
                    }
                });
    }

    /**
     * 可以继续使用操作符 线程转换
     */
    public static <T> ObservableTransformer<T, T> applySchedulers() {
        return observable -> observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }
}
